<template>
	<view>
		<block v-if="user">
			<block v-if="!notifyData || !status">
				<uv-empty mode="search" v-if="devices.length === 0" text="无可用设备" :marginTop="160" :icon="empty">
					<uv-button type="primary" text="扫描蓝牙设备" @click="searchBle" style="width:600rpx;margin:75rpx 75rpx 15rpx 75rpx;"></uv-button>
					<uv-button type="success" text="扫码连接" @click="scan" style="width:600rpx;margin:15rpx 75rpx;"></uv-button>
				</uv-empty>
				<view style="padding:25rpx;margin:25rpx;background:#fff;border-radius:25rpx;" v-else>
					<uv-search shape="round" :showAction="false" clearabled @change="filterDevices"></uv-search>
					<uv-list padding="25rpx">
						<block v-for="(item, index) in devices">
						<uv-list-item
							v-if="item.name.indexOf(searchName) > -1"
							:key="index"
							:clickable="true"
							:show-extra-icon="true"
							:extra-icon="{ icon: 'order', size: '22' }"
							:title="item.name"
							@click="connectDevice(item)"
							show-arrow
						></uv-list-item>
						</block>
					</uv-list>
				</view>
			</block>
			<block v-else>
				<device
					ref="device"
					v-if="notifyData"
					:notify-data="notifyData"
					:setting-fm-data="settingFmData"
					:setting-all-data="settingAllData"
					:setting-data="settingData"
					:setting4GData="setting4GData"
					:settingFkqData="settingFkqData"
					:settingDdfData="settingDdfData"
					@readSetting="readSetting"
					@sendCommand="sendCommand"
					@fetchData="fetchData"
					@stopFetchData="stopFetchData"
				></device>
			</block>
			<view style="margin:25rpx;padding-bottom:25rpx;" @click="disconnect" v-if="status || devices.length > 0"><uv-button type="info">断开连接</uv-button></view>
		</block>
		<block v-else>
			<uv-empty mode="search" text="未登录 , 请登录后连接蓝牙设备" :marginTop="160" :icon="empty">
				<uv-button type="primary" text="去登录" @click="login" style="width:600rpx;margin:75rpx;"></uv-button>
			</uv-empty>
		</block>
	</view>
</template>
<script>
import { routeUrl, toast, modal, loading, strToHex, deepClone } from '@/util';
import { convert, crc32, buf2hex } from '@/util/bluetooth';
import { command } from '@/util/formatter';
import { mySet } from '@/util/constant';
import device from '@/components/device';
import { mapGetters } from 'vuex';
import { login } from '@/api/user'
export default {
	components: {
		device
	},
	data() {
		return {
			searchName:'',
			empty: 'https://cdn.uviewui.com/uview/empty/search.png',
			status: false,
			devices: [],
			device: {
				name: '',
				deviceId: '', //已连接设备uuid
				services: '', //连接设备的服务
				characteristics: '', //连接设备的状KT
				serviceId: '', // 服务id,
				writeCharacteristicsId: '',
				notifyCharacteristicsId: ''
			},
			ReadHOLD: 'FF0302650008',
			notifyData: '',
			settingData: '',
			settingFmData: '',
			settingAllData: '',
			settingFkqData:'',
			settingDdfData:'',
			setting4GData_1: '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
			setting4GData_2: '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
			setting4GData_3: '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
			setting4GData_4: '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
			deviceNameAttr:'YFWL',
			connectSend:1,
			connectSendStr:'YFWL',
			polling:1,
			pollingInter:5,
			connectTimeout:30,
			// settingFkqData: '0b030000000000000000000000000000000000000001000100010001101800010002000300049082',
			// setting4GData:'0b03000038393836303444343232323238303134393832340000323134333232393938383737323236000000000000630001237a7777772e7a6573692e636f6d2e636e000000000000000000000000000000000000000000000000003244565a76306f684e31596b000000000000000000000000000000000000000000000000000000007573657200000000000000000000000000000000000000000000000000000000000000000000000044657631403324350000000000000000000000000000000000000000000000000000000000000000422f5946574c2f514630303031000000000000000000000000000000000000000000000000000000522f3131314535394437363133384131383100000000000000000000000000000000000000000000522f313131453539443736313338413138312f4457000000000000000000000000000000000000009387',
			// notifyData: '104510 4532 0FFF 0001 0002 0000 0000 0000 0000 E0EE'
			// settingData: '0C03012C000100 0BF34E'
			// settingAllData: '0C030003000C06EF536402625E2500000000000000000000000000000000000000000E1000000000B398'
		};
	},
	onLoad() {
		uni.onBLEConnectionStateChange(res => {
			this.status = res.connected;
			if (!res.connected) {
				this.closeBluetoothAdapter();
			}
		});
	},
	onPullDownRefresh() {
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	},
	computed: {
		...mapGetters(['user']),
		setting4GData(){
			if(this.setting4GData_1.length > 12 && this.setting4GData_2.length > 12 && this.setting4GData_3.length > 12 && this.setting4GData_4.length > 12){
				const data_1 = this.setting4GData_1.substr(0,this.setting4GData_1.length-4)
				const data_2 = this.setting4GData_2.substr(8)
				const data_3 = this.setting4GData_3.substr(8)
				const data_4 = this.setting4GData_4.substr(8)
				return data_1 + data_2.slice(0,data_2.length-4) + data_3.slice(0,data_3.length-4) + data_4
			}
			return  ''
		}
	},
	watch: {
		user: {
			handler(newVal) {
				if (!newVal) {
					this._disConnect();
				}
			},
			deep: true,
			immediate: true
		},
		device: {
			handler(newVal) {
				if (newVal.deviceId) {
					uni.setNavigationBarTitle({
						title: newVal.name
					});
				} else {
					uni.setNavigationBarTitle({
						title: '蓝牙调试工具'
					});
				}
			},
			deep: true,
			immediate: true
		}
	},
	methods: {
		filterDevices(value){
			this.searchName = value
		},
		scan(){
			uni.scanCode({
				success: (res) => {
					const deviceId = res.result
					const deviceNameAttr = this.deviceNameAttr.split(',');
					const deviceFindResults = []
					deviceNameAttr.forEach(item => {
						if (deviceId.indexOf(item) > -1) {
							deviceFindResults.push(deviceId);
						}
					});
					if(deviceFindResults.length === 0){
						toast('无效二维码')
						return
					}
					uni.openBluetoothAdapter({
						success: (res) => {
							uni.getBluetoothAdapterState({
								success:(res) => {
									uni.startBluetoothDevicesDiscovery({
										success: res => {
											loading('搜索中');
											uni.onBluetoothDeviceFound(res => {
												res.devices.forEach((item) => {
													if(item.name === deviceId){
														this.connectDevice(item)
													}
												})
											});
											setTimeout(() => {
												//加个延迟、目的是为了设备搜索完毕再获取列表，不然获取为空列表
												// 获取设备列表
												if (!this.device.deviceId) {
													toast('未搜索到任何设备，请重试');
													this.stopBluetoothDevicesDiscovery()
												}
											}, (this.connectTimeout || uni.getStorageSync('connectTimeout')) * 1000);
										},
										fail: err => {
											console.log(err);
										}
									});
								}
							})
						}
					})
				},
				fail: (err) => {
					toast('无效二维码')
				}
			})
		}, 
		stopBluetoothDevicesDiscovery(){
			uni.stopBluetoothDevicesDiscovery({
				success: function(res) {
					console.log('停止搜索成功');
				},
				fail: function(err) {
					console.log('停止搜索失败', err);
				}
			});
			uni.hideLoading();
		},
		login() {
			uni.showToast({
				title:'登录'
			})
			login({phone:'13520946139',password:'Dev1@3$5'}).then((res) => {
				console.log(res)
				uni.showToast({
					title:res.msg
				})
			}).catch((err) => {
				uni.showToast({
					title:'no'
				})
				console.log(err)
			})
			// routeUrl('/pages/index/login');
		},
		readSetting(idx, showCommand = 0) {
			let addr = [613];
			let len = [10];
			switch (idx) {
				case 4:
					{
						addr = [600];
						len = [10];
					}
					break;
				case 2:
					{
						addr = [300];
						len = [2];
					}
					break;
				case 3:
					{
						addr = [0];
						len = [21];
					}
					break;
				case 5:
					{
						addr = [395,435,475,350];
						len = [40,40,40,45];
					}
					break;
				case 6:
					{
						addr = [800];
						len = [17];
					}
					break;
				case 7:
					{
						addr = [800];
						len = [17];
					}
					break;
			}
			
			for(let idx = 0; idx<addr.length; idx++){
				setTimeout(() => {
					uni.writeBLECharacteristicValue({
						//发送指令
						deviceId: this.device.deviceId,
						serviceId: this.device.serviceId,
						characteristicId: this.device.writeCharacteristicsId,
						value: convert(command(addr[idx], len[idx], '03')),
						success: res => {
							console.log(res,command(addr[idx], len[idx], '03'))
							if (showCommand) {
								toast('操作成功');
							}
						},
						fail: err => {
							console.log(err);
						}
					});
				}, 500 * idx);
			}
		},
		disconnect() {
			modal('操作确认', '确定要断开连接吗？', () => {
				this._disConnect();
			});
		},
		_disConnect() {
			if (this.device.deviceId) {
				uni.closeBLEConnection({
					deviceId: this.device.deviceId,
					success: res => {
						this.closeBluetoothAdapter();
						this.$refs.device.resetStates()
					},
					fail(res) {
						console.log(res);
					}
				});
			} else {
				this.closeBluetoothAdapter();
			}
		},
		initBle() {
			uni.openBluetoothAdapter({
				success: res => {
					//已打开
					uni.getBluetoothAdapterState({
						//蓝牙的匹配状态
						success: row => {
							// 开始搜索蓝牙设备
							uni.showLoading({
								title: '搜索中'
							});
							this.startBluetoothDeviceDiscovery();
						},
						fail(error) {
							toast('查看手机蓝牙是否打开');
						}
					});
				},
				fail: err => {
					toast('查看手机蓝牙是否打开');
				}
			});
		},
		// 开始搜索蓝牙设备
		startBluetoothDeviceDiscovery() {
			uni.startBluetoothDevicesDiscovery({
				success: res => {
					uni.onBluetoothDeviceFound(res => {
						let devices_filter = res.devices.filter(obj => {
							const name = obj.name;
							let deviceFindResults = [];
							const deviceNameAttr = this.deviceNameAttr.split(',');
							deviceNameAttr.forEach(item => {
								if (name.indexOf(item) > -1) {
									deviceFindResults.push(obj);
								}
							});
							return deviceFindResults.length > 0;
						});
						this.devices = this.devices.concat(devices_filter)
					});
					setTimeout(() => {
						//加个延迟、目的是为了设备搜索完毕再获取列表，不然获取为空列表
						// 获取设备列表
						if (this.devices.length === 0) {
							toast('未搜索到任何设备，请重试');
						}
						this.stopBluetoothDevicesDiscovery()
					}, (this.connectTimeout || uni.getStorageSync('connectTimeout')) * 1000);
				},
				fail: err => {
					console.log(err);
				},
				complete: () => {
					// uni.hideLoading()
				}
			});
		},
		searchBle() {
			if (this.device.deviceId) {
				uni.closeBLEConnection({
					deviceId: this.device.deviceId,
					success: res => {
						this.closeBluetoothAdapter('init');
					},
					fail(res) {
						console.log(res);
					}
				});
			} else {
				this.closeBluetoothAdapter('init');
			}
		},
		// 连接选中设备
		connectDevice(device) {
			this.device = device;
			loading('连接中');

			uni.createBLEConnection({
				deviceId: this.device.deviceId,
				success: res => {
					this.getBLEDeviceServices();
				},
				fail: res => {
					toast('连接失败，请重试');
				},
				complete: () => {
					uni.hideLoading()
				}
			});
		},
		setMtu() {
			uni.setBLEMTU({
				deviceId: this.device.deviceId,
				mtu: 128,
				success: res => {
					console.log('设置最大值成功');
				}
			});
		},
		// 获取服务uuid
		getBLEDeviceServices() {
			setTimeout(() => {
				uni.getBLEDeviceServices({
					deviceId: this.device.deviceId,
					success: res => {
						this.device.services = res.services;
						const validServices = res.services.filter(val => {
							return val.uuid.indexOf('0000FFF0') > -1;
						});
						if (validServices.length > 0) {
							this.device.serviceId = validServices[0].uuid;
							/* 获取连接设备的所有特征值 */
							this.getBLEDeviceCharacteristics();
						}
					},
					fail: res => {
						toast('获取服务失败');
					}
				});
			}, 1000);
		},
		// 获取特征值
		getBLEDeviceCharacteristics() {
			setTimeout(() => {
				uni.getBLEDeviceCharacteristics({
					deviceId: this.device.deviceId,
					serviceId: this.device.serviceId,
					success: res => {
						this.characteristics = res.characteristics;
						uni.hideLoading();
						this.notifyData = '1';
						for (var obj of res.characteristics) {
							let current_uuid = obj.uuid;
							if (current_uuid.indexOf('FFF1') !== -1) {
								this.device.writeCharacteristicsId = current_uuid;
							}
							if (current_uuid.indexOf('FFF2') > -1) {
								this.device.notifyCharacteristicsId = current_uuid;
								this.notifyBLECharacteristicValueChange();
								if (this.connectSend || uni.getStorageSync('connectSend')) {
									this.sendConnectStr();
									setTimeout(()=> {
										this.readSetting(3)
									},2000)
								}
								if (this.polling || uni.getStorageSync('polling')) {
									this.getbleData();
								}
							}
						}
					},
					fail: res => {
						toast('获取特征值失败');
					}
				});
			}, 1000);
		},
		sendConnectStr() {
			uni.writeBLECharacteristicValue({
				//发送指令
				deviceId: this.device.deviceId,
				serviceId: this.device.serviceId,
				characteristicId: this.device.writeCharacteristicsId,
				value: convert(strToHex(this.connectSendStr || uni.getStorageSync('connectSendStr'))),
				success: res => {
					this.setMtu();
				},
				fail: err => {
					console.log(err);
				}
			});
		},
		// 启用低功耗蓝牙设备特征值变化时的 notify 功能
		notifyBLECharacteristicValueChange() {
			setTimeout(() => {
				uni.notifyBLECharacteristicValueChange({
					state: true,
					type: 'notification',
					deviceId: this.device.deviceId,
					serviceId: this.device.serviceId,
					characteristicId: this.device.notifyCharacteristicsId,
					success: res => {
						this.readData();
					}
				});
			}, 1000);
		},
		getbleData() {
			this.result()
		},
		result(){
			setTimeout(() => {
				uni.writeBLECharacteristicValue({
					//发送指令
					deviceId: this.device.deviceId,
					serviceId: this.device.serviceId,
					characteristicId: this.device.writeCharacteristicsId,
					value: convert(command(613, 8, '03')),
					success: res => {
						// console.log(res);
					},
					fail: err => {
						console.log(err);
					}
				});
			}, 500);
			
			setTimeout(() => {
				uni.writeBLECharacteristicValue({
					//发送指令
					deviceId: this.device.deviceId,
					serviceId: this.device.serviceId,
					characteristicId: this.device.writeCharacteristicsId,
					value: convert(command(800, 17, '03')),
					success: res => {
						// console.log(res);
					},
					fail: err => {
						console.log(err);
					}
				});
			}, 500);
		},
		fetchData(){
			this.inter = setInterval(() => {
				this.result();
			}, (this.pollingInter || uni.getStorageSync('pollingInter')) * 1000);
		},
		stopFetchData(){
			clearInterval(this.inter)
		},
		// 读取数据
		readData() {
			uni.onBLECharacteristicValueChange(res => {
				var value = buf2hex(res.value).toLowerCase();
				if (value.length > 8 && value.substr(2, 2) !== '06' && value.substr(2, 2) !== '10') {
					const addr = value.substr(4, 4).toLowerCase();
					if (addr === '0000' && value.length > 40) {
						this.settingAllData = value;
					}
					if (addr === '0258' && value.length >= 16) {
						this.settingFmData = value;
					}
					if (addr === '012c' && value.length >= 16) {
						this.settingData = value;
					}
					if (addr === '0265' && value.length >= 16) {
						this.notifyData = value;
					}
					if (addr === '015e' && value.length >= 16) {
						this.setting4GData_1 = value;
					}
					if (addr === '018b' && value.length >= 16) {
						this.setting4GData_2 = value;
					}
					if (addr === '01b3' && value.length >= 16) {
						this.setting4GData_3 = value;
					}
					if (addr === '01db' && value.length >= 16) {
						this.setting4GData_4 = value;
					}
					if (addr === '0320' && value.length >= 16) {
						this.settingFkqData = value;
						this.settingDdfData = value;
					}
				}
			});
		},
		// 关闭蓝牙模块
		closeBluetoothAdapter(isInit = '') {
			uni.closeBluetoothAdapter({
				success: res => {
					clearInterval(this.inter);
					this.status = false;
					this.devices = [];
					this.services = [];
					this.device = {};
					this.deviceId = '';
				},
				fail: err => {
					clearInterval(this.inter);
					this.status = false;
					this.devices = [];
					this.services = [];
					this.device = {};
					this.deviceId = '';
				},
				complete: () => {
					if (isInit === 'init') {
						this.initBle();
					}
					// this.setting4GData_1 = ''
					// this.setting4GData_2 = ''
					// this.setting4GData_3 = ''
					// this.setting4GData_4 = ''
					this.notifyData = ''
					this.settingData = ''
					this.settingFmData =  ''
					this.settingAllData =  ''
					this.settingFkqData = ''
					this.settingDdfData = ''
				}
			});
		},
		sendCommand(value,type='single',time=500,msg='设置中',callback=null) {
			uni.writeBLECharacteristicValue({
				//发送指令
				deviceId: this.device.deviceId,
				serviceId: this.device.serviceId,
				characteristicId: this.device.writeCharacteristicsId,
				value: convert(value),
				success: res => {
					if(type === 'single'){
						loading(msg)
						setTimeout(() => {
							if(callback){
								callback()
							} else {
								toast('操作成功');
								uni.hideLoading()
							}
						},time)
					}
				},
				fail: err => {
					console.log(err);
				}
			});
		}
	}
};
</script>
<style lang="scss">
page {
	background: #f0f0f0;
}
.round-fixed-container {
	position: fixed;
	bottom: 192rpx;
	right: 64rpx;
	width: 120rpx;
	text-align: center;
	.round-container {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		line-height: 120rpx;
		text-align: center;
		color: #fff;
		background: #3c9cff;
	}
	.font-small {
		font-size: 24rpx;
	}
}
</style>
